<template>
    <div id="new-bracelet">
        <el-breadcrumb separator="/" class="common-bread">
            <el-breadcrumb-item :to="{ path: '/bracelet' }">手环管理</el-breadcrumb-item>
            <el-breadcrumb-item>{{operationText}}手环</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="form mt10 contentBox">
            <div class="list_head">
                <span class="head_name">手环信息</span>
                <el-button type="primary" @click="$router.push('/bracelet')" class="fr ml10">返回</el-button>
                <el-button type="primary" @click="save" class="fr" v-if="canEdit">保存</el-button>
            </div>
            <el-form label-width="120px" :model="form" :rules="rules" :inline="true" ref="form">
                <el-form-item label="设备号：" prop="deviceNum">
                    <el-input v-model="form.deviceNum" :disabled="!canEdit"></el-input>
                </el-form-item>
                <el-form-item label="软件版本：" prop="osVersion" required>
                    <el-select v-model="form.osVersion" :disabled="!canEdit">
                        <el-option :label='item' v-for="item in osVersions" :key="item" :value="item"></el-option>
                    </el-select>
                </el-form-item><br>
                <el-form-item label="设备型号：" prop="deviceModel" required>
                    <el-select v-model="form.deviceModel" :disabled="!canEdit">
                        <el-option :label='item' v-for="item in deviceModels" :key="item" :value="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="生产厂商：" prop="manufacturer" required>
                    <el-select v-model="form.manufacturer" :disabled="!canEdit">
                        <el-option :label='item' v-for="item in manufacturers" :key="item" :value="item"></el-option>
                    </el-select>
                </el-form-item><br>
                <el-form-item label="入库人员：" prop="inUserName">
                    <el-input v-model="form.inUserName" disabled></el-input>
                </el-form-item>
                <el-form-item label="入库日期：" prop="inDate">
                    <el-date-picker v-model="form.inDate" type="date" format="yyyy/MM/dd" :disabled="!canEdit">
                    </el-date-picker>
                </el-form-item><br>
                <el-form-item label="手环状态：" prop="bindState" v-if="!canEdit">
                    <el-select v-model="form.bindState" :disabled="form.bindState=='1'">
                        <el-option label='未使用' value="0"></el-option>
                        <el-option label='使用中' value="1" v-if="form.bindState==1"></el-option>
                        <el-option label='已破损' value="2"></el-option>
                        <el-option label='维修中' value="3"></el-option>
                        <el-option label='已报废' value="4"></el-option>
                    </el-select>

                    <el-button type="primary" @click="changeState" v-if="form.bindState!=1">确定更改</el-button>
                </el-form-item>
            </el-form>
            <div v-if="!canEdit">
                <div class="list_head">
                    <span class="head_name">手环使用信息</span>
                    <el-button type="primary" @click="oepnDialog" class="fr" v-if="canBind">新增绑定</el-button>
                </div>

                <el-table :data="list" border class="mt10">
                    <el-table-column type="index" label="序号">
                    </el-table-column>
                    <el-table-column prop="bindDate" label="绑定日期">
                    </el-table-column>
                    <el-table-column prop="schoolName" label="使用学校">
                    </el-table-column>
                    <el-table-column prop="studentName" label="使用学生姓名">
                    </el-table-column>
                    <el-table-column prop="studentNum" label="学生学籍号">
                    </el-table-column>
                    <el-table-column prop="className" label="当前班级">
                    </el-table-column>
                    <el-table-column prop="bindState" label="手环状态">
                    </el-table-column>
                    <el-table-column prop="cancelDate" label="解绑日期">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button size="small" type="text" @click="cancelBind(scope.row)"
                                v-if="scope.row.bindState=='使用中'">解绑</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <el-dialog title="新增绑定" :visible.sync="dialogFormVisible">
                <el-form label-width="130px" :model="dialogForm" ref="dialogForm">
                    <el-form-item label="设备号：">
                        {{this.form.deviceNum}}
                    </el-form-item>
                    <el-form-item label="设备型号：">
                        {{this.form.deviceModel}}
                    </el-form-item>
                    <el-form-item label="使用学生学籍号：" prop="studentNum">
                        <el-input v-model="dialogForm.studentNum"></el-input>
                        <el-button type="primary" @click="getStudInfo">匹配学生信息</el-button>
                    </el-form-item>
                    <el-form-item label="绑定日期：" prop="bindDate">
                        <el-date-picker v-model="dialogForm.bindDate" type="date" format="yyyy/MM/dd">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="使用学校：" prop="schoolName" v-if="dialogForm.schoolName">
                        {{this.dialogForm.schoolName}}
                    </el-form-item>
                    <el-form-item label="使用班级：" prop="className" v-if="dialogForm.className">
                        {{this.dialogForm.className}}
                    </el-form-item>
                    <el-form-item label="使用学生姓名：" prop="studentName" v-if="dialogForm.studentName">
                        {{this.dialogForm.studentName}}
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="submitBind">确 定</el-button>
                    <el-button type="primary" @click="dialogFormVisible=false">取 消</el-button>
                </div>
            </el-dialog>

        </div>
    </div>
</template>

<script>
    import { mapState, mapActions } from "vuex";

    export default {
        data() {
            return {
                id: "",
                operationText: "新增",
                deviceModels: [],//设备型号
                manufacturers: [],//生产商
                osVersions: [],//版本
                dialogFormVisible: false,
                canEdit: true,
                canBind: false,
                schools: [],
                form: {
                    deviceNum: "",
                    osVersion: "",
                    deviceModel: "",
                    manufacturer: "",
                    inDate: new Date(),
                    inUserName: "",
                    inUser: "",
                    className: "",
                    bindState: "0"
                },
                dialogForm: {
                    schoolName: "",
                    schoolId: "",
                    className: "",
                    bindDate: new Date(),
                    studentNum: "",
                    studentName: ""
                },
                list: [],
                rules: {
                    deviceNum: [
                        { required: true, message: "设备号不能为空", trigger: "blur" }
                    ]
                }
            }
        },
        computed: mapState({ user: state => state.user }),
        mounted() {
            this.id = this.$util.getUrlParam("id");

            this.$util.setStore("braceletSelect", "1");
            this.getExtraInfo();

            if (this.id) {
                this.operationText = "编辑";
                this.canEdit = false;
                this.getBindHistory();
                this.getBasicInfo();
            } else {
                this.form.inUserName = this.user.userName;
                this.form.inUser = this.user.userId;
            }
        },
        methods: {
            save() {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        this.canEdit = false;

                        this.$axios.post("/adminapi/bangle/v1/save", {
                            deviceNum: this.form.deviceNum,
                            deviceModel: this.form.deviceModel,
                            manufacturer: this.form.manufacturer,
                            osVersion: this.form.osVersion,
                            inUser: this.form.inUser,
                            inDate: this.form.inDate ? new Date(this.form.inDate).getTime() : ""
                        }).then(response => {
                            if (response.data.error == 10000) {
                                this.canEdit = false;
                                this.canBind = true;
                                this.id = this.form.deviceNum;
                                this.$util.successMsg("保存成功");
                            } else {
                                this.canEdit = true;
                                this.$util.errorMsg(response.data.message);
                            }
                        })
                    }
                })

            },
            // 获取设备附属信息（厂商、版本、型号）列表
            getExtraInfo() {
                this.$axios.post("/adminapi/bangle/v1/ancillary").then(response => {
                    if (response.data.error == 10000) {
                        this.deviceModels = response.data.data.deviceModels;
                        this.manufacturers = response.data.data.manufacturers;
                        this.osVersions = response.data.data.osVersions;

                        this.form.deviceModel = this.deviceModels[0];
                        this.form.osVersion = this.osVersions[0];
                        this.form.manufacturer = this.manufacturers[0];
                    }
                })
            },
            //获取设备基础信息
            getBasicInfo() {
                this.$axios.post("/adminapi/bangle/v1/get/basic", { deviceNum: this.id }).then(response => {
                    if (response.data.error == 10000) {
                        let info = response.data.data;
                        if (info.bindState == 0) this.canBind = true;
                        this.form = {
                            deviceNum: info.deviceNum,
                            osVersion: info.osVersion,
                            deviceModel: info.deviceModel,
                            manufacturer: info.manufacturer,
                            inDate: new Date(info.inDate),
                            inUserName: info.inUserName,
                            inUser: info.inUser,
                            bindState: info.bindState + ""
                        }
                    }
                })
            },
            //获取设备绑定记录
            getBindHistory() {
                this.$axios.post("/adminapi/bangle/v1/get/bindInfo", { deviceNum: this.id }).then(response => {
                    if (response.data.error == 10000) {
                        let list = response.data.data;
                        this.list = [];
                        list.forEach(item => {
                            item.bindDate = item.bindDate ? new Date(item.bindDate).format("yyyy/MM/dd") : "";
                            item.cancelDate = item.cancelDate ? new Date(item.cancelDate).format("yyyy/MM/dd") : "";
                            let className = item.grade + item.number + "班";
                            item.className = item.className ? className + `（${item.className}）` : className;
                            switch (item.bindState) {
                                case 1:
                                    item.bindState = "使用中";
                                    this.canBind = false;
                                    break;
                                case 2:
                                    item.bindState = "已解绑";
                                    break;
                            }

                            this.list.push(item);
                        });
                    }
                })
            },
            //打开对话框
            oepnDialog() {
                if (this.$refs.dialogForm) this.$refs.dialogForm.resetFields();
                this.dialogForm.schoolName = "";
                this.dialogForm.className = "";
                this.dialogForm.studentName = "";
                this.dialogForm.studentNum = "";
                this.dialogFormVisible = true;
            },
            submitBind() {
                if (!this.dialogForm.studentNum || !this.dialogForm.bindDate || !this.dialogForm.studentNum.trim()) return;
                this.dialogFormVisible = false;

                this.$axios.post("/adminapi/bangle/v1/bind", {
                    deviceNum: this.form.deviceNum,
                    bindDate: new Date(this.dialogForm.bindDate).getTime(),
                    stuNum: this.dialogForm.studentNum,
                    isForce: 0
                }).then(response => {
                    this.dialogFormVisible = false;
                    if (response.data.error == 10000) {
                        this.getBindHistory();
                        this.form.bindState = "1";
                        this.$util.successMsg("绑定成功");
                    } else {
                        this.$confirm(response.data.message + "，是否仍要继续绑定？", "温馨提示", this.$util.confirmBtnText).then(() => {
                            this.$axios.post("/adminapi/bangle/v1/bind", {
                                deviceNum: this.form.deviceNum,
                                bindDate: new Date(this.dialogForm.bindDate).getTime(),
                                stuNum: this.dialogForm.studentNum,
                                isForce: 1
                            }).then(data => {
                                if (data.data.error == 10000) {
                                    this.getBindHistory();
                                    this.form.bindState = "1";
                                    this.$util.successMsg("绑定成功");
                                } else {
                                    this.$util.errorMsg(response.data.message);
                                }
                            })
                        })
                    }
                })
            },
            //匹配学生信息
            getStudInfo() {
                if (!this.dialogForm.studentNum || !this.dialogForm.studentNum.trim()) return;

                let params = {
                    pageSize: 10,
                    pageNum: 1,
                    studentNumber: this.dialogForm.studentNum.trim()
                };
                this.$axios.get("/adminapi/v1/user/student/list", {
                    params: params
                }).then(response => {
                    if (response.data.error == 10000) {
                        if (!response.data.data) {
                            this.dialogForm.schoolName = "";
                            this.dialogForm.className = "";
                            this.dialogForm.studentName = "";
                            return this.$util.errorMsg("该学籍号暂无匹配信息");
                        };

                        let info = response.data.data.content[0];
                        this.dialogForm.schoolName = info.schoolName;
                        info.grade = this.$util.gradeFormat(info.grade * 1);
                        let className = info.grade + info.claNumber + "班";
                        this.dialogForm.className = info.className ? className + `（${info.className}）` : className;
                        this.dialogForm.studentName = info.name;
                        this.dialogForm.studentNum = info.studentNumber;

                    } else {
                        this.$util.errorMsg(response.data.message);
                    }
                })
            },
            //解除绑定
            cancelBind(row) {
                this.$confirm("确认要将当前手环解绑吗？", "温馨提示", this.$util.confirmBtnText).then(() => {
                    this.$axios.post("/adminapi/bangle/v1/cancel", {
                        deviceNum: row.deviceNum
                    }).then(data => {
                        if (data.data.error == 10000) {
                            this.getBindHistory();
                            this.canBind = true;//解绑之后可以新增绑定；
                            this.form.bindState = "0";
                            this.$util.successMsg("解绑成功");
                        } else {
                            this.$util.errorMsg(response.data.message);
                        }
                    })
                }).catch(() => { })

            },
            //更改手环状态
            changeState() {
                this.$axios.post("/adminapi/bangle/v1/state/update", {
                    deviceNum: this.form.deviceNum,
                    state: this.form.bindState * 1
                }).then(response => {
                    if (response.data.error == 10000) {
                        if (this.form.bindState != 0) {
                            this.canBind = false;
                        } else {
                            this.canBind = true;
                        }
                        return this.$util.successMsg("状态更新成功");
                    };
                })
            }
        }
    }
</script>
<style scoped>
    #new-bracelet {
        height: inherit;
    }

    #new-bracelet .el-input {
        width: 200px;
    }
</style>